import { useRouter } from "@tarojs/taro";
import { Text, View } from "@tarojs/components";
import { useBoolean, useCreation } from "ahooks";

import ByRow from "@/components/ui/ByRow";
import ByText from "@/components/ui/ByText";
import Card from "@/components/common/Card";
import Moment from "@/components/app/Moment";
import Page from "@/components/common/Page";
import ByIcon from "@/components/ui/ByIcon";
import ByCell from "@/components/ui/ByCell";
import PopupRecord from "./components/PopupRecord";
import PlanConstructionCardView from "./components/PlanConstructionCardView";

import ApiCrm from "@/api/crm";
import ApiWork from "@/api/work";
import useFetch from "@/hooks/useFetch";
import useGetHolidayList from "@/hooks/useGetHolidayList";
import { getDaysBetweenDate, getPeriodEndDate } from "@/utils";

import { ContractInfo } from "@/types/contract";
import { IntentCustomerData } from "@/types/customer";
import { ConstructionPlanDetail } from "@/types/construction";

export default () => {
  const { params } = useRouter();
  const intentCustomerId = Number(params.intentCustomerId);

  const [holidays] = useGetHolidayList();

  // 获取施工执行详情
  const { data } = useFetch<ConstructionPlanDetail>(
    ApiCrm.getConstructionPlanDetail,
    { defaultParams: [{ intentionCustomerId: intentCustomerId }] }
  );

  // 合同信息
  const { data: contractInfoData } = useFetch<ContractInfo>(
    ApiWork.getContractInfo,
    {
      defaultParams: [{ intentCustomerId }],
      onAfter: (res) => res.contractInfo,
    }
  );

  // 获取客户信息
  const { data: customerData } = useFetch<{
    intentCustomer: IntentCustomerData;
  }>(ApiCrm.customerDetail, {
    defaultParams: [{ intentCustomerId }],
  });

  // 记录弹窗
  const [visible, { setFalse, setTrue }] = useBoolean();

  const dateView = useCreation(() => {
    if (contractInfoData && data && holidays) {
      const {
        realBeginDate,
        isSkipHoliday,
        contractDuration = 0,
      } = contractInfoData;

      // 合同结束时间:  只有存在realBeginDate时，才需要计算合同时间
      const contractEndDate = realBeginDate
        ? getPeriodEndDate(
            realBeginDate,
            contractDuration,
            holidays,
            isSkipHoliday ?? data.isSkipHoliday
          )
        : "";

      const isStarted = !!data?.realStartDate;

      // 施工开始时间
      const startDate = isStarted ? data.realStartDate : data.planStartDate;
      // 施工结束时间
      // const endDate = isStarted ? data.realEndDate : data.planFinishDate;
      const endDate = data.realEndDate || data.planFinishDate;

      // 施工周期（不用管是否节假日施工）
      const duration = getDaysBetweenDate(startDate, endDate);

      return {
        // 合同工期
        contractEndDate,
        contractBeginDate: realBeginDate,
        contractDuration,

        // 施工工期
        startDate,
        endDate,
        duration,
      };
    }
  }, [contractInfoData, data, holidays]);

  return (
    data && (
      <>
        <Page>
          <View className="flex flex-col h-screen py-4">
            <View className="flex-auto px-4">
              <Card className="mb-4">
                <ByRow content="between" align="center" className="font-bold">
                  <Text>{customerData?.intentCustomer.customerName}</Text>

                  <ByIcon
                    name="Clock"
                    className="text-second"
                    size={30}
                    onClick={setTrue}
                  />
                </ByRow>

                <View className="mt-2 text-sm text-third">
                  {customerData?.intentCustomer.decorationFullAddress}
                </View>
              </Card>

              <Card className="mb-6">
                <ByCell size="small" label="合同工期:">
                  <Moment value={dateView?.contractBeginDate} type="month" />
                  <Text className="px-1">～</Text>
                  <Moment value={dateView?.contractEndDate} type="month" />
                  <ByText className="pl-3">
                    <ByText size="sm" type="second">
                      拟定
                    </ByText>
                    {dateView?.contractDuration}个工作日
                  </ByText>
                </ByCell>
                <ByCell size="small" label="施工工期:">
                  <Moment value={dateView?.startDate} type="month" />
                  <Text className="px-1">～</Text>
                  <Moment value={dateView?.endDate} type="month" />
                  <ByText className="pl-3">
                    <ByText size="sm" type="second">
                      拟定
                    </ByText>
                    {dateView?.duration}个工作日
                    {/* {data?.isSkipHoliday ? "工作日" : "天"} */}
                  </ByText>
                </ByCell>

                <ByCell
                  size="small"
                  label={`节假日${data?.isSkipHoliday ? "不" : ""}施工`}
                >
                  预计
                  <Moment
                    value={data.planFinishDate}
                    type="year"
                    className="px-1"
                  />
                  完工
                </ByCell>
              </Card>

              {data.formConstructionPlan?.map((item, index) => (
                <View key={item.constructionId + "_" + index}>
                  <PlanConstructionCardView source={item} />
                </View>
              ))}
            </View>
          </View>
        </Page>

        {/* 修改记录弹窗 */}
        {visible && (
          <PopupRecord
            intentCustomerId={intentCustomerId}
            onCancel={setFalse}
          />
        )}
      </>
    )
  );
};
